package dt

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"analysis-ss/models"
)

type Centers struct {
	DataTable
}

func (cs *Centers) GetTableInfo(start, length int, args ...string) error {
	centerId := ""
	if len(args) == 1 {
		centerId = args[0]
	}

	// 起始位置和当前页面信息
	cs.Start = start
	cs.Length = length

	// 记录总数
	count, err := queryCentersCount(centerId)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.RecordsTotal = count
	cs.RecordsFiltered = count
	// 当前记录信息
	centers, _, err := queryCenters(centerId, start, length)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.Data = centers

	return nil
}

// 查询中心
func queryCentersCount(centerId string) (int, error) {
	var count int
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `select
                  count(distinct(center_id))
                  from
                  t_schedule
                  where 1=1 `
	if centerId != "" && centerId != "0" {
		sqlStr = fmt.Sprint(sqlStr, ` and  center_id =`, centerId)
	}

	err := o.Raw(sqlStr).QueryRow(&count)
	return count, err
}

func queryCenters(centerId string, start, length int) ([]models.Center, int64, error) {
	var centers []models.Center
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `select
	          distinct(center_id) as center_id,
	          center_name as center_name
	          from
	          t_schedule where 1=1
	           `
	if centerId != "" && centerId != "0" {
		sqlStr = fmt.Sprint(sqlStr, ` and  center_id =`, centerId)
	}

	sqlStr = fmt.Sprint(sqlStr, ` order by ( center_id + 1 )  limit `, start, ",", length)
	num, err := o.Raw(sqlStr).QueryRows(&centers)

	return centers, num, err
}
